package com.cn.servlet;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.JsonMapper;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	
	private JsonMapper binder=JsonMapper.nonDefaultMapper();
	private UserService userService=new UserServiceImpl();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type=req.getParameter("type");
		if("login".equals(type)) {
			//使用map获取登陆页面的用户信息
			Map<String,String[]> map=req.getParameterMap();
			//获取验证码
			String veryCode=req.getParameter("veryCode");
			
			//获取随机生成的验证码
			String validateCode=(String) req.getSession().getAttribute("validateCode");
			
			if(validateCode.equals(veryCode)) {
				User user=new User();
				try {
					//将登陆页面输入的信息封装user
					BeanUtils.populate(user, map);
					String pwd=req.getParameter("hu_password");
					//给用户密码加密
					user=userService.queryUserByNameAndPwd(user);
					if(user==null) {
						//失败登陆返回登陆界面
						req.getRequestDispatcher("/login.jsp").forward(req, resp);
					}else {
						//登陆成功到首页
						//将用户信息放到session域中
						req.getSession().setAttribute("user",user);
						//开始建立用户cookie
						Cookie cookie=new Cookie("userName",user.getHu_user_name()+"&"+pwd);
						cookie.setMaxAge(3600*24*7);
						resp.addCookie(cookie);
						req.getRequestDispatcher("/index.jsp").forward(req, resp);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else {
				//登陆失败!
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		}else if("logout".equals(type)) {
			//开始注销,清空所有的用户信息
			req.getSession().invalidate();
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
}
